package com.yupi.picturebackend.api.aliyunai;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.yupi.picturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.yupi.picturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yupi.picturebackend.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.yupi.picturebackend.api.aliyunai.wordtopicture.model.CreateWenToPictureRequest;
import com.yupi.picturebackend.api.aliyunai.wordtopicture.model.CreateWenToPictureResponse;
import com.yupi.picturebackend.api.aliyunai.wordtopicture.model.GetWenToPictureTaskResponse;
import com.yupi.picturebackend.exception.BusinessException;
import com.yupi.picturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AliYunAiApi {

    //获取配置文件中的秘钥
    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    // 创建扩图任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    // 查询扩图任务状态
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    // 创建文生图任务地址
    public static final String CREATE_WEN_TO_PICTURE_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis";

    // 查询文生图任务状态
    public static final String GET_WEN_TO_PICTURE_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建扩图任务
     * @param createOutPaintingTaskRequest
     * @return
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest){
        // 参数校验
        if (createOutPaintingTaskRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"扩图参数为空");
        }
        // 发送请求
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                // 必须开启异步处理，设置为enable。
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        // 响应处理,写在括号里可自动释放资源
        try (HttpResponse response = httpRequest.execute()){
            //相应失败
            if (!response.isOk()){
                log.error("AI扩图请求失败，响应状态码：{}，响应内容：{}", response.getStatus(), response.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"AI扩图请求失败");
            }
            //相应成功，获取响应对象
            CreateOutPaintingTaskResponse createOutPaintingTaskResponse = JSONUtil.toBean(response.body(), CreateOutPaintingTaskResponse.class);
            if (createOutPaintingTaskResponse.getCode() != null){
                log.error("AI扩图失败，错误码：{}，错误信息：{}", createOutPaintingTaskResponse.getCode(), createOutPaintingTaskResponse.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"AI扩图失败");
            }
            return createOutPaintingTaskResponse;
        }
    }

    /**
     * 查询创建扩图任务结果
     * @param taskId
     * @return
     */
    public GetOutPaintingTaskResponse getOutPaintingTask(String taskId){
        // 参数校验
        if (taskId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"任务id为空");
        }
        // 发送请求
        String url = String.format(GET_OUT_PAINTING_TASK_URL, taskId);
        try (HttpResponse response = HttpRequest.get(url)
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .execute()) {
            //相应失败
            if (!response.isOk()){
                log.error("扩图接口调用请求失败，响应状态码：{}，响应内容：{}", response.getStatus(), response.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取任务结果失败");
            }
            return JSONUtil.toBean(response.body(), GetOutPaintingTaskResponse.class);
        }
     }

    /**
     * 创建文生图任务
     * @param createWenToPictureRequest
     * @return
     */
     public CreateWenToPictureResponse createWenToPictureTask(CreateWenToPictureRequest createWenToPictureRequest){
        // 参数校验
         if (createWenToPictureRequest == null){
             throw new BusinessException(ErrorCode.PARAMS_ERROR,"文生图参数不能为空");
         }
         System.out.println(createWenToPictureRequest.getInput().getPrompt());
         // 发送请求
         HttpRequest httpRequest = HttpRequest.post(CREATE_WEN_TO_PICTURE_TASK_URL)
                 .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                 // 必须开启异步处理，设置为enable。
                 .header("X-DashScope-Async", "enable")
                 .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                 .body(JSONUtil.toJsonStr(createWenToPictureRequest));
         // 响应处理,写在括号里可自动释放资源
         try (HttpResponse response = httpRequest.execute()){
             //相应失败
             if (!response.isOk()){
                 log.error("AI文生图请求失败，响应状态码：{}，响应内容：{}", response.getStatus(), response.body());
                 throw new BusinessException(ErrorCode.OPERATION_ERROR,"AI文生图请求失败");
             }
             //相应成功，获取响应对象
             CreateWenToPictureResponse createWenToPictureResponse = JSONUtil.toBean(response.body(), CreateWenToPictureResponse.class);
             if (createWenToPictureResponse.getCode() != null){
                 log.error("AI文生图失败，错误码：{}，错误信息：{}", createWenToPictureResponse.getCode(), createWenToPictureResponse.getMessage());
                 throw new BusinessException(ErrorCode.OPERATION_ERROR,"AI文生图失败");
             }
             return createWenToPictureResponse;
         }
     }

    /**
     * 查询文生图任务结果
     * @param taskId
     * @return
     */
     public GetWenToPictureTaskResponse getWenToPictureTask(String taskId){
         // 参数校验
         if (taskId == null){
             throw new BusinessException(ErrorCode.PARAMS_ERROR,"任务id为空");
         }
         // 发送请求
         String url = String.format(GET_WEN_TO_PICTURE_TASK_URL, taskId);
         try (HttpResponse response = HttpRequest.get(url)
                 .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                 .execute()) {
             //相应失败
             if (!response.isOk()){
                 log.error("文生图接口调用请求失败，响应状态码：{}，响应内容：{}", response.getStatus(), response.body());
                 throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取任务结果失败");
             }
             return JSONUtil.toBean(response.body(), GetWenToPictureTaskResponse.class);
         }
     }
}
